﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.IO;

namespace IntelligentCMS
{
    /// <summary>
    /// PluginManager manages plugins.
    /// </summary>
    public class CMSPluginManager
    {

        public CMSPluginManager()
        {
            

        }

        private void Load() 
        {
            /*
            CMSDbDataLayer newDataLayer = new CMSDbDataLayer(string.Empty, CMSDbDataHelper.Microsoft);
            newDataLayer.AddQuery("SELECT [FileName] FROM CMS_Plugins");
            newDataLayer.NonQuery = false;
            newDataLayer.Execute();

            for (int i = 0; i < newDataLayer.Data.Rows.Count; i++)
            {
                CMSPlugin newPlugin = new CMSPlugin();
                newPlugin.LoadFromDB(newDataLayer.Data.Rows[i].ItemArray[i].ToString());
                plugins.Add(newPlugin);

            }
             * */

        }



        private List<CMSPlugin> plugins = new List<CMSPlugin>();

        public List<CMSPlugin> Plugins
        {

            get
            {
                return plugins;
            }

        }

        /// <summary>
        /// Deletes the plugin.
        /// </summary>
        /// <param name="name">The name.</param>
        public void Delete(string name)
        {
            int index = -1;
            for (int i = 0; i < plugins.Count; i++ )
            {
                if (plugins[i].TheAssembly.FullName == name)
                {
                    index = i;

                }

            }

            if (index > -1)
            {
                plugins[index].Remove();
                plugins.RemoveAt(index);
            }

        }

        /// <summary>
        /// Registers the plugin.
        /// </summary>
        /// <param name="name">The name.</param>
        public void Add(string name)
        {
            CMSPlugin newPlugin = new CMSPlugin(name);
            plugins.Add(newPlugin);
        }

        

        /// <summary>
        /// Scans the plugin directory, removes missing plugins, registers new ones.
        /// </summary>
        public void PluginDirectoryWatcher()
        {
            DirectoryInfo newInfo = new System.IO.DirectoryInfo("plugins");
            

            foreach (FileInfo f in newInfo.GetFiles(".dll"))
            {

                /*
                CMSDbDataLayer newDataLayer = new CMSDbDataLayer(string.Empty, CMSDbDataHelper.Microsoft);
                
                newDataLayer.AddQuery("SELECT [FileName] FROM CMS_Plugins WHERE [FileName] = '" + f.FullName + "'");
                newDataLayer.NonQuery = false;
                newDataLayer.Execute();

                if (newDataLayer.Data.Rows.Count == 0)
                {
                    Add(f.FullName);

                }
                */
            }

        }
    }
}
